package wq.gdky005.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

public class GetFileMD5 {
	
	/** 获取大文件的MD5 */
	public static String getMd5ByFile(File file) {
		String value = null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			MappedByteBuffer byteBuffer = in.getChannel().map(
					FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}

	/** 获取普通文件和小文件的MD5 */
	public static String getMd5BySmallFile(File file) {
		String value = null;
		FileInputStream in = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			byte[] buffer = new byte[4096];
			int length = -1;
			while ((length = in.read(buffer)) != -1) {
				md5.update(buffer, 0, length);
			}
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException ex) {
			}
		}
		return value;
	}
	
	public static void main(String[] args) { //对文件进行MD5校验
		
		
		String filePath = "c:\\AndroidDB";
		File  f = new File(filePath);
		File[] files = f.listFiles();
		for (int i = 0; i < files.length; i++) {
			getFileMd5(files[i]);
			
		}
		
		
		
		
		
	}

	private static void getFileMd5(File file) {
		System.out.println("文件名字" + file.getName());
		System.out.println("文件大小是" + file.length());
		System.out.println("Md5ByFile:" + getMd5ByFile(file));
		System.out.println("Md5BySmallFile:" + getMd5BySmallFile(file));
	}

}
